//使用惰性单例模式实现只请求一次权限
//管理单例
var getSingle = function (fn) {
    var result;
    return function () {
        return result || (result = fn.apply(this,arguments))
    }
}

var getAuthorityFunc = function () {
    var userInfo;

    var access_token = localStorage.getExpire("access_token");
    if(access_token){
        userInfo=localStorage.getExpire("userInfo");
    }else{
        layui.use(['layer'], function () {
            var $ = layui.jquery;
            var layer = layui.layer;
            layer.msg("你还没有登录", {icon: 2, time: 1500});
        })
        setTimeout(function () {
            top.location.href=loginPageUrl;
        },2500)
    }
    return userInfo;
}

//获取权限
var getAuthority = getSingle(getAuthorityFunc);

// window.onload=function(){
//     //示例获取权限方法
//     var data1 = getAuthority()
// };


Storage.prototype.setExpire = (key, value, expire) => {
    let obj = {
        data: value,
        time: Date.now(),
        expire: expire
    };
    //localStorage 设置的值不能为对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
}

Storage.prototype.getExpire = key => {
    let val = localStorage.getItem(key);
    if (!val) {
        return val;
    }
    val = JSON.parse(val);
    if (Date.now() - val.time > val.expire) {
        localStorage.removeItem(key);
        return null;
    }else{
        var obj = {
            data: val.data,
            time: Date.now(),
            expire: val.expire
        }
        localStorage.setItem(key,JSON.stringify(obj));
    }
    return val.data;
}

window.onload=function () {
    var ele = document.getElementById("loginOut");
    if(ele){
        ele.addEventListener("click",function(){
            loginOutFunc();
        })
    }
}

//注销方法
function loginOutFunc(){
    localStorage.clear();
    top.location.href=loginPageUrl;
}